
import os
import sys

import django



os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'seckill_java_topy.settings')
# 初始化 Django 环境
django.setup()
# from django.conf import settings
# print("INSTALLED_APPS:", settings.INSTALLED_APPS)
# 获取项目根目录
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# sys.path.append(BASE_DIR)



import asyncio

import uvicorn
from fastapi_seckill.app_config import app
from fastapi import FastAPI,Request
from api import seckill_api
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse
from orders.tasks import createOrder
from starlette.middleware.cors import CORSMiddleware
from fastapi_seckill.redis_fast import RedisHelper
if os.name == 'nt':  # Windows 平台
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
# 配置 CORS
origins = [
    "http://localhost:8000",  # Django 前端地址
    "http://127.0.0.1:8000"   # 如果使用 IP 地址访问
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  # 允许的前端域名
    allow_credentials=True,  # 是否允许携带 Cookie
    allow_methods=["*"],     # 允许的 HTTP 方法
    allow_headers=["*"],     # 允许的 HTTP 头
)

@app.on_event("startup")
async def startup_event():
    try:
        redis_helper = RedisHelper()
        await redis_helper.connect()
        app.state.redis = redis_helper  # 存储整个RedisHelper实例
        print("Redis连接成功！")
    except Exception as e:
        print(f"启动失败: {e}")
        import sys
        sys.exit(1)  # 终止应用

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """
    捕获请求验证错误并返回详细信息。
    """
    return JSONResponse(
        status_code=422,
        content={"detail": exc.errors(), "body": exc.body},
    )

@app.get("/")
async def root():
    return {"message": "FastAPI 和 Django 混合架构运行成功！"}
app.include_router(seckill_api,prefix="/seckill",tags=["秒杀接口"])



if __name__ == '__main__':
    uvicorn.run("main:app", port=8001, reload=True)